package SocketLearn;


import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-06 6:54
 * @description 对象流，涉及到序列化和反序列化
 * 对象的序列化机制：将对象转换为与平台无关的二进制流(序列化)，其他程序读取并恢复成对象（反序列化）
 *
 * 1.ObjectInputStream和ObjectOutputStream
 * 2.作用：用于存储和读取基本数据类型或对象的处理流
 * 3.要想一个java对象是可序列化的，需要满足相应的要求。见Person.java
 */
public class ObjectStream {
    /**
     * 序列化过程：将内存中的java对象保存在磁盘中或通过网络传输出去
     * 使用ObjectOutputStream实现
     *
     */
    @Test
    public void testObjectOutputStream() throws IOException {
        String path="D:\\Java Learn\\IOLearnTestFile\\test1\\object.txt";
        String path2="D:\\Java Learn\\IOLearnTestFile\\test1\\person.txt";

        ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream(path));
        oos.writeObject(new String("我爱北京天安门"));
        oos.flush();

        ObjectOutputStream oos2=new ObjectOutputStream(new FileOutputStream(path2));
        oos2.writeObject(new Person("李恩乐",22));
        oos2.flush();

        oos.close();
        oos2.close();
    }

    /**
     * 反序列化：将磁盘文件中的对象还原为内存中的一个对象
     * @throws IOException
     * @throws ClassNotFoundException
     */
    @Test
    public void testObjectInputStream() throws IOException, ClassNotFoundException {
        String path="D:\\Java Learn\\IOLearnTestFile\\test1\\object.txt";
        String path2="D:\\Java Learn\\IOLearnTestFile\\test1\\person.txt";

        ObjectInputStream ois= new ObjectInputStream(new FileInputStream(path));
        String str=(String)ois.readObject();

        ObjectInputStream ois2=new ObjectInputStream(new FileInputStream(path2));
        Person p=(Person)ois2.readObject();

        System.out.println(str);
        System.out.println(p);
        ois.close();
        ois2.close();
    }
}
